<template>
  <el-dialog :append-to-body="true" :close-on-click-modal="false" :visible.sync="dialog" title="导入" width="500px">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="160px">
      <el-form-item v-if="hasOrgSet" label="所属组织机构" prop="busMainData.sysOrgCode">
        <OrgsetTreeSelect v-model="form.busMainData.sysOrgCode" style="width: 300px;" placeholder="选择组织机构" />
      </el-form-item>
      <el-form-item label="上传文件" prop="attachmentList">
        <el-upload
          ref="upload"
          :show-file-list="true"
          :on-success="handleFileSuccess"
          :on-error="handleFileError"
          :on-remove="handleFileRemove"
          :on-preview="handlePreview"
          :headers="headers"
          :limit="1"
          :file-list="form.attachmentList"
          :action="fileUploadUrl"
          accept=".xlsx"
          multiple
          class="avatar-uploader">
          <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传1个xlsx件
            <el-button type="text" @click="downloadTemplate">模板下载</el-button>
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { fileUploadUrl, downloadSysAttachment } from '@/api/system/fileMng'
import { getToken, getUserInfo } from '@/utils/auth'
import { postRequest, postRequestDownload } from '@/api/data'
import OrgsetTreeSelect from '@/views/components/OrgsetTreeSelect'

export default {
  components: { OrgsetTreeSelect },
  props: {
    sup_this: {
      type: Object,
      default: null,
      required: true
    },
    importUrl: {
      type: String,
      default: '',
      requried: true
    },
    importTemplateUrl: {
      type: String,
      default: '',
      requried: true
    },
    hasOrgSet: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    const validFile = (rule, value, callback) => {
      if (this.form.attachmentList && this.form.attachmentList.length === 0) {
        callback(new Error('请上传文件'))
      } else if (this.form.attachmentList && this.form.attachmentList.length !== 1) {
        callback(new Error('只上传1个文件'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      dialog: false,
      style: 'width: 184px',
      headers: {
        'X-AUTH-TOKEN': getToken()
      },
      fileUploadUrl: fileUploadUrl(),
      form: {
        attachmentList: [],
        busMainData: {
          sysOrgCode: getUserInfo().orgCode
        }
      },
      rules: {
        'attachmentList': [
          { required: true, trigger: 'blur', validator: validFile }
        ],
        'busMainData.sysOrgCode': [
          { required: true, message: '请选择组织机构', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
  },
  methods: {
    downloadTemplate() {
      const exportFileName = Date.parse(new Date()) + '.xlsx'
      postRequestDownload(this.importTemplateUrl, {}, exportFileName).then(res => {
      }).catch(err => {
        console.log(err)
      })
    },
    cancel() {
      this.resetForm()
    },
    handleFileSuccess(res, file, fileList) {
      if (res.code !== '1000') {
        this.$notify({
          title: '上传失败:' + res.msg,
          type: 'error',
          duration: 2500
        })
        this.handleFileRemove(file, fileList)
        return
      }
      const sysAttachment = res.data
      sysAttachment.uid = file.uid
      this.form.attachmentList.push(sysAttachment)
    },
    handleFileRemove(file, fileList) {
      this.form.attachmentList = this.form.attachmentList.filter(t => t.uid !== file.uid)
    },
    // 监听上传失败
    handleFileError(e, file, fileList) {
      const msg = e.msg || e
      this.$notify({
        title: msg,
        type: 'error',
        duration: 2500
      })
    },
    handlePreview(file) {
      const exportFileName = file.fileName || (Date.parse(new Date()) + file.fileType)
      downloadSysAttachment(file.filePath, exportFileName)
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.doImport()
        }
      })
    },
    doImport() {
      postRequest(this.importUrl, this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '导入成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.sup_this.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
    }
  }
}
</script>
